﻿package com.projects.xenia.add_activities;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.UUID;

import com.projects.xenia.R;
import com.projects.xenia.documents_classes.Documents_Order;
import com.projects.xenia.documents_classes.Documents_Order.DocLine;
import com.projects.xenia.global_modules.MainGlobalModule;
import com.projects.xenia.prompts_activities.Activity_NumericPrompt;

import com.projects.xenia.ref_classes.GoodRefObject;
import com.projects.xenia.ref_classes.GoodsRefItem;
import com.projects.xenia.ref_classes.OffersBonusRefItem;
import com.projects.xenia.ref_classes.OffersConditionsAssortmensRefItem;
import com.projects.xenia.ref_classes.OffersConditionsRefItem;
import com.projects.xenia.ref_classes.OffersRefItem;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class Activity_OffersConditions extends Activity {

	private Context Ctx;
	private ExpandableListView offers_expandableListView;
	private CustomExpandableListViewAdapter offers_expandableListViewAdapter;
	
	private OffersRefItem Offer;
	private ArrayList<OffersConditionsRefItem> OffersList;
	
	private TextView offerscondition_descr;
	private TextView offerscondition_valuetype;
	private TextView offerscondition_logicaltype_descr;	
	
	private ImageView OffersConditions_BackWard;	
	private ImageView OffersConditions_DescriptionButton;	
	private Documents_Order DocumentClass;
	
	private int CurrentGroupIndx;	
	private int CurrentChildIndx;
	private int CurrentBonusesIndx;
	
	private HashMap<String, Double> GoodsInOrders;
	
	private TabHost tabs;
	
	private ListView bonus_ListView;	
	private CustomListViewAdapter bonus_ListViewAdapter;	
	private ArrayList <OffersBonusRefItem> bonus_List;
	
	private String CustomersPriceCategory;
	
	private final int IDR_InputCountForChild = 0;
	private final int IDR_OpenSubChild = 1;	
	private final int IDR_InputCountForRequiredDistribute = 2;
	private final int IDR_InputCountForAutoDistribute = 3;
	private final int IDR_InputCountForBonuses = 4;
	
	private GoodRefObject GoodObject;
	
	private boolean DiscountsEnable;
	
	private void insertBonusToDB () {
		
		/// запись бонусов БД
		ArrayList <OffersBonusRefItem > BonusForInsert = new ArrayList <OffersBonusRefItem > (); 
		
		for (OffersBonusRefItem bi : bonus_List){							
			if (bi.offers_conditions_id!=null) {
				if (bi.bonus_count_value>0){
					BonusForInsert.add(bi);
				}
			}
			else {
				BonusForInsert.add(bi);
			}	
		}						
		
		for (OffersBonusRefItem bi : BonusForInsert){
			ContentValues BonusInsertValues = new ContentValues();
			BonusInsertValues.put("id", UUID.randomUUID().toString().toUpperCase());
			BonusInsertValues.put("hdoc_id", DocumentClass.Line.hdoc_id);
			BonusInsertValues.put("tdoc_id", DocumentClass.Line.hdoc_id);
			BonusInsertValues.put("offers_id", Offer.id);
			BonusInsertValues.put("offers_conditions_id", bi.offers_conditions_id);							
			BonusInsertValues.put("offers_conditions_bonus_id", bi.id);	
			
			if (bi.goods==null){
				BonusInsertValues.put("goods_id", "");
			}
			else
			{
				BonusInsertValues.put("goods_id", bi.goods.id);	
			}						
			
			BonusInsertValues.put("bonus_count", bi.bonus_count_value);
			BonusInsertValues.put("comment", bi.comment);							
			MainGlobalModule.DBE.insert("xdoc_Orders_B", null, BonusInsertValues);
			
			/// если бонус с ценой или скидкой для конкретного товара тогда изменим цену товара и посчитаем скидку
			
			if ((bi.bonus_price!=0)&(bi.bonus_count==0)&(bi.goods!=null)) {
				
				DocLine docit = DocumentClass.DocLineCollection.get(bi.goods.id);
				
				if  (docit!=null) {
					
					double _price = GoodObject.GetGoodsPrice(bi.goods.id, null);
					if (DiscountsEnable & bi.goods.isfolder == 0) {
						double _price0 = GoodObject.GetGoodPriceByDiscount(bi.goods.id);
						if (_price0 != 0) {
							_price = _price0; 
						}
					}
					
					DocumentClass.Line.id = docit.id;
					DocumentClass.Line.hdoc_id = docit.hdoc_id;
					DocumentClass.Line.goods_id = docit.goods_id;
					DocumentClass.Line.goods_descr = docit.goods_descr;  
					DocumentClass.Line.factor = docit.factor;
					DocumentClass.Line.goods_feature_id = docit.goods_feature_id;
					DocumentClass.Line.goods_measures_id = docit.goods_measures_id;
					DocumentClass.Line.goods_measures_descr = docit.goods_measures_descr;
					
					if (bi.bonus_price>0) {
						DocumentClass.Line.price = bi.bonus_price;
						_price = bi.bonus_price;
					}					
					
					if (bi.bonus_discount!=0) {
						_price = Math.round(_price*100)/100;
						DocumentClass.Line.price = DocumentClass.Line.price;
					}
					
					DocumentClass.Line.ordervalue = docit.ordervalue;					
					DocumentClass.Line.order_sum = docit.factor * docit.ordervalue * docit.price;
					DocumentClass.InsertUpdateLine();	
				}
								
			}
			
			/// если бонус со скидкой на все выбранные тогда посчитаем скидку всех выбранных товаров 
			
			if ((bi.bonus_discount!=0)&(bi.bonus_count==0)&(bi.goods==null)) {
				
				for (OffersConditionsRefItem oi : OffersList) {					
					
					if (oi.id.equals(bi.offers_conditions_id) & oi.offers_condition_count_value>0) {						
					
						for (OffersConditionsAssortmensRefItem ai : oi.offers_assortmets_items) {					
							
							DocLine docit = DocumentClass.DocLineCollection.get(ai.goods.id);
							
							if  (docit!=null) {							
								double _price = GoodObject.GetGoodsPrice(ai.goods.id, null);
								if (DiscountsEnable & ai.goods.isfolder == 0) {
									double _price0 = GoodObject.GetGoodPriceByDiscount(ai.goods.id);
									if (_price0 != 0) {
										_price = _price0; 
									}
								}
								
								DocumentClass.Line.id = docit.id;
								DocumentClass.Line.hdoc_id = docit.hdoc_id;
								DocumentClass.Line.goods_id = docit.goods_id;
								DocumentClass.Line.goods_descr = docit.goods_descr;  
								DocumentClass.Line.factor = docit.factor;
								DocumentClass.Line.goods_feature_id = docit.goods_feature_id;
								DocumentClass.Line.goods_measures_id = docit.goods_measures_id;
								DocumentClass.Line.goods_measures_descr = docit.goods_measures_descr;		
								
								if (bi.bonus_discount!=0) {
									_price = Math.round(_price*100)/100;
									DocumentClass.Line.price = _price;
								}
								
								DocumentClass.Line.ordervalue = docit.ordervalue;					
								DocumentClass.Line.order_sum = docit.factor * docit.ordervalue * docit.price;
								DocumentClass.InsertUpdateLine();	
							}									
							
						}
						
					}
					
					
				}
			
				
						
			}
			
		}
		
	}
	
	private void insertOffersToDB (OffersConditionsAssortmensRefItem ai, HashMap<String, Double> gh) {
		
		if (ai.offers_condition_count_value > 0) {
			
			double existvalue = 0;
			
			if (gh.get(ai.goods.id) != null) {
				existvalue = gh.get(ai.goods.id);
			}
				
			existvalue += ai.offers_condition_count_value;
			gh.put(ai.goods.id, existvalue);
			
			DocLine docit = DocumentClass.DocLineCollection.get(ai.goods.id);
			
			if (docit!=null) {
			
				double doc_ordervalue = docit.ordervalue * docit.factor;
			
				if (doc_ordervalue < existvalue) {
					doc_ordervalue = existvalue;
				}							
				
				DocumentClass.Line.id = docit.id;
				DocumentClass.Line.hdoc_id = docit.hdoc_id;
				DocumentClass.Line.goods_id = ai.goods.id;
				DocumentClass.Line.goods_descr = ai.goods.descr;  
				DocumentClass.Line.factor = 1;
				DocumentClass.Line.goods_feature_id = "";
				DocumentClass.Line.goods_measures_id = ai.goods.measure_base_id;
				DocumentClass.Line.goods_measures_descr = ai.goods.measure_base_descr;
				DocumentClass.Line.price = ai.goods.price;
				DocumentClass.Line.ordervalue = doc_ordervalue;					
				DocumentClass.Line.order_sum = doc_ordervalue * ai.goods.price;
				
			}
				
			else {	
				
				DocumentClass.Line.id = UUID.randomUUID().toString().toUpperCase();
				DocumentClass.Line.hdoc_id = DocumentClass.Head.id;
				DocumentClass.Line.goods_id = ai.goods.id;
				DocumentClass.Line.goods_descr = ai.goods.descr;  
				DocumentClass.Line.factor = 1;
				DocumentClass.Line.goods_feature_id = "";
				DocumentClass.Line.goods_measures_id = ai.goods.measure_base_id;
				DocumentClass.Line.goods_measures_descr = ai.goods.measure_base_descr;
				DocumentClass.Line.price = ai.goods.price;
				DocumentClass.Line.ordervalue = ai.offers_condition_count_value;					
				DocumentClass.Line.order_sum = ai.offers_condition_count_value * ai.goods.price;
			
			}
			
				DocumentClass.InsertUpdateLine();
					
				ContentValues OffersInsertValues = new ContentValues();
				OffersInsertValues.put("id", UUID.randomUUID().toString().toUpperCase());
				OffersInsertValues.put("hdoc_id", DocumentClass.Line.hdoc_id);
				OffersInsertValues.put("tdoc_id", DocumentClass.Line.id);
				OffersInsertValues.put("offers_id", Offer.id);
				OffersInsertValues.put("offers_conditions_id", ai.offers_condition_id);
				OffersInsertValues.put("goods_id", ai.goods.id);
				OffersInsertValues.put("offervalue", ai.offers_condition_count_value);
				MainGlobalModule.DBE.insert("xdoc_Orders_O", null, OffersInsertValues);
	
		}
		
		
	}
		
	private void AcceptOffer () { 
		
		MainGlobalModule.DBE.beginTransaction();
		
		HashMap<String, Double> gh = new HashMap<String, Double>(); 
		
		for (OffersConditionsRefItem oi : OffersList) {	
			
			for (OffersConditionsAssortmensRefItem ai : oi.offers_assortmets_items) {		
				
				if (ai.SubOffersConditionsAssortmensRefItem!=null) {				
					/// удаляем вложенные товары и условия
					for (OffersConditionsAssortmensRefItem aix:ai.SubOffersConditionsAssortmensRefItem) {						
						double oldoffers_condition_count_value = MainGlobalModule.GetOffersConditionsGoodsCount (DocumentClass.Head.id,ai.offers_condition_id,aix.goods.id);
						if (oldoffers_condition_count_value > 0) {
							DocLine docit = DocumentClass.DocLineCollection.get(aix.goods.id);							
							if (docit!=null) {								
								double doc_ordervalue = docit.ordervalue * docit.factor;
								doc_ordervalue -= oldoffers_condition_count_value;
								DocumentClass.Line.id = docit.id;
								DocumentClass.Line.hdoc_id = docit.hdoc_id;
								DocumentClass.Line.goods_id = aix.goods.id;
								DocumentClass.Line.goods_descr = aix.goods.descr;  
								DocumentClass.Line.factor = 1;
								DocumentClass.Line.goods_feature_id = "";
								DocumentClass.Line.goods_measures_id = aix.goods.measure_base_id;
								DocumentClass.Line.goods_measures_descr = aix.goods.measure_base_descr;
								DocumentClass.Line.price = aix.goods.price;
								DocumentClass.Line.ordervalue = doc_ordervalue;					
								DocumentClass.Line.order_sum = doc_ordervalue * ai.goods.price;
								DocumentClass.InsertUpdateLine();
							}
							// удалим условие
							MainGlobalModule.DBE.delete("xdoc_orders_o", "hdoc_id = ? and offers_conditions_id=? and goods_id = ? ", new String [] {DocumentClass.Head.id, oi.id, aix.goods.id});
						}
						
					}					
				}
				
 				/// удаляем товар и условие
				else {					
						double oldoffers_condition_count_value = MainGlobalModule.GetOffersConditionsGoodsCount (DocumentClass.Head.id,ai.offers_condition_id,ai.goods.id);
						if (oldoffers_condition_count_value>0) {						
							DocLine docit = DocumentClass.DocLineCollection.get(ai.goods.id);							
							if (docit!=null) {								
								double doc_ordervalue = docit.ordervalue * docit.factor;
								doc_ordervalue -= oldoffers_condition_count_value;							
								DocumentClass.Line.id = docit.id;
								DocumentClass.Line.hdoc_id = docit.hdoc_id;
								DocumentClass.Line.goods_id = ai.goods.id;
								DocumentClass.Line.goods_descr = ai.goods.descr;  
								DocumentClass.Line.factor = 1;
								DocumentClass.Line.goods_feature_id = "";
								DocumentClass.Line.goods_measures_id = ai.goods.measure_base_id;
								DocumentClass.Line.goods_measures_descr = ai.goods.measure_base_descr;
								DocumentClass.Line.price = ai.goods.price;
								DocumentClass.Line.ordervalue = doc_ordervalue;					
								DocumentClass.Line.order_sum = doc_ordervalue * ai.goods.price;
								DocumentClass.InsertUpdateLine();
							}
						// удалим условие
						MainGlobalModule.DBE.delete("xdoc_orders_o", "hdoc_id = ? and offers_conditions_id=? and goods_id = ? ", new String [] {DocumentClass.Head.id, oi.id, ai.goods.id});						
						}							
				}
			
				// 	удалим бонус
				MainGlobalModule.DBE.delete("xdoc_orders_b", "hdoc_id = ? and offers_conditions_id=?", new String [] {DocumentClass.Head.id, oi.id});
				
				// вставляем если есть условия
				if (oi.offers_condition_bonus_value > 0) {
					if (ai.SubOffersConditionsAssortmensRefItem!=null) {
						for (OffersConditionsAssortmensRefItem oaix:ai.SubOffersConditionsAssortmensRefItem) {
							insertOffersToDB (oaix,gh);	
						}
					}
					else {
						insertOffersToDB (ai,gh);	
					}
				}				
			}	
			
		};
		
		/// записываем бонусы
		
		insertBonusToDB ();
		
		MainGlobalModule.DBE.setTransactionSuccessful();
		MainGlobalModule.DBE.endTransaction();
		
		finish ();
		
	}
	
	private void FinishActivity () {
	
		
		boolean HaveBonus = false;
		
		//for (OffersConditionsRefItem oi : OffersList) {
			//if (MainGlobalModule.ExistsBonusByOffers(DocumentClass.Head.id, oi.id)) {
				//HaveBonus = true;
				//break;
			//}
			//if (oi.offers_condition_bonus_value > 0) {
				//HaveBonus = true;
				//break;
			//}
		//}			
			
		
		//if (HaveBonus) {
			AlertDialog.Builder builder = new AlertDialog.Builder(Ctx);
			builder.setMessage("Принять акцию , и перенести изменения в заказ ?");
			builder.setPositiveButton("Да", new DialogInterface.OnClickListener() {			
				@Override
				public void onClick(DialogInterface dialog, int which) {			
					AcceptOffer ();
				}
			});
			
			builder.setNegativeButton("Нет", new DialogInterface.OnClickListener() {			
				@Override
				public void onClick(DialogInterface dialog, int which) {			
					finish ();
				}
			});
			
			builder.create().show();
			
		//}
		//else
		//{
			//finish ();
		//}
			
		
	}
		
	private void GetOffersAssortmentByGroupId (String GroupId, OffersConditionsAssortmensRefItem _OffersConditionsAssortmensRefItem) {
		
		Cursor GoodsCursor = MainGlobalModule.GetGoodsRefCursorByParentId(GroupId, CustomersPriceCategory, DocumentClass.Head.id, DocumentClass.Head.acctype, DocumentClass.Head.departments_id,0);	
		if (GoodsCursor.getCount() > 0){
			GoodsCursor.moveToFirst();				
			while (GoodsCursor.isAfterLast()==false) {
				
				GoodsRefItem gi = new GoodsRefItem ();
				gi.id = GoodsCursor.getString(0);
				gi.parentid = GoodsCursor.getString(1);
				gi.article = GoodsCursor.getString(2);
				gi.descr = GoodsCursor.getString(3);
				gi.isfolder = GoodsCursor.getInt(4);
				gi.weight = GoodsCursor.getDouble(5);
				gi.volume = GoodsCursor.getDouble(6);
				gi.minimum_order = GoodsCursor.getDouble(7);
				gi.price = GoodsCursor.getDouble(8);
				gi.rest  = GoodsCursor.getDouble(9);				
				gi.measure_base_id  = GoodsCursor.getString(10);				
				gi.measure_base_descr = GoodsCursor.getString(11);
				gi.measure_base_factor = GoodsCursor.getDouble(12);
				
				gi.position = _OffersConditionsAssortmensRefItem.SubOffersConditionsAssortmensRefItem.size();				
				
				OffersConditionsAssortmensRefItem it = new OffersConditionsAssortmensRefItem ();				

				it.offers_condition_id = _OffersConditionsAssortmensRefItem.offers_condition_id;
				it.goods = gi;
				it.offers_condition_sku_count = 0;
				it.offers_condition_value = 0;				
				it.offers_condition_sku_count_value = 0;
				it.offers_condition_count_value = 0;
				it.offers_condition_sum_value = 0;

				if (!(GoodsInOrders==null)) {		
					if (GoodsInOrders.get(it.goods.id + it.offers_condition_id)!=null) {
						it.offers_condition_count_value = GoodsInOrders.get(it.goods.id + it.offers_condition_id);
					}
					else
					{
						it.offers_condition_count_value = 0;
					}  	
				}
				it.offers_condition_sum_value = it.offers_condition_count_value * it.goods.price;
				
				
				DocLine docit = DocumentClass.DocLineCollection.get(it.goods.id);
				if (!(docit==null)) {				
					it.indoc_count= docit.ordervalue*docit.factor;
					it.indoc_sum = docit.order_sum;							
				}	
				else
				{
					it.indoc_count= 0;
					it.indoc_sum = 0;
				}				
				
				_OffersConditionsAssortmensRefItem.offers_condition_count_value += it.offers_condition_count_value; 
				_OffersConditionsAssortmensRefItem.offers_condition_sum_value +=it.offers_condition_sum_value;
				_OffersConditionsAssortmensRefItem.indoc_count += it.indoc_count; 
				_OffersConditionsAssortmensRefItem.indoc_sum +=it.indoc_sum;				

				if (it.goods.isfolder != 1) {
					_OffersConditionsAssortmensRefItem.SubOffersConditionsAssortmensRefItem.add(it);	
				}								
				
				if (gi.isfolder == 1) {											
					GetOffersAssortmentByGroupId (gi.id,_OffersConditionsAssortmensRefItem);	
				}
			
				GoodsCursor.moveToNext();
			}
			
			GoodsCursor.close();
		}
	}
	
	private void GetOffersConditions () {
		
		OffersList = new ArrayList<OffersConditionsRefItem> ();
		
		Cursor OffersConditionsCursor = MainGlobalModule.DBE.rawQuery("select id,offers_id,offers_condition_numb,offers_condition_sku_count,offers_condition_value from xref_Offers_Conditions where offers_id = ? order by offers_condition_numb asc", new String []{Offer.id});
		
		if (OffersConditionsCursor.getCount()>0) {
			OffersConditionsCursor.moveToFirst();
			while (!OffersConditionsCursor.isAfterLast()){
			
				OffersConditionsRefItem _OffersRefItem = new OffersConditionsRefItem ();
				_OffersRefItem.id = OffersConditionsCursor.getString(0);
				_OffersRefItem.offers_condition_numb = OffersConditionsCursor.getInt(2);
				_OffersRefItem.offers_condition_sku_count = OffersConditionsCursor.getInt(3);
				_OffersRefItem.offers_condition_value = OffersConditionsCursor.getDouble(4);				
				
				
				Cursor OffersConditionsAssortmensCursor = MainGlobalModule.DBE.rawQuery("select a.offers_condition_id, a.goods_id, a.offers_condition_sku_count, a.offers_condition_value from xref_Offers_Conditions_Assortments a left outer join xref_goods g on a.goods_id = g.id where a.offers_condition_id = ? order by g.descr_long", new String [] {_OffersRefItem.id});
				if (OffersConditionsAssortmensCursor.getCount()>0) {
					_OffersRefItem.offers_assortmets_items = new ArrayList<OffersConditionsAssortmensRefItem> ();
					OffersConditionsAssortmensCursor.moveToFirst();
					while (!OffersConditionsAssortmensCursor.isAfterLast()){
						
						OffersConditionsAssortmensRefItem _OffersConditionsAssortmensRefItem = new OffersConditionsAssortmensRefItem ();						
						
						_OffersConditionsAssortmensRefItem.offers_condition_id = OffersConditionsAssortmensCursor.getString(0); 
						_OffersConditionsAssortmensRefItem.goods = MainGlobalModule.GetGoodsRefItemByGoodsId(OffersConditionsAssortmensCursor.getString(1), CustomersPriceCategory ,DocumentClass.Head.firms_id, DocumentClass.Head.acctype, DocumentClass.Head.departments_id);
						_OffersConditionsAssortmensRefItem.offers_condition_sku_count = OffersConditionsAssortmensCursor.getInt(2);
						_OffersConditionsAssortmensRefItem.offers_condition_value = OffersConditionsAssortmensCursor.getDouble(3);
						
						if (!(GoodsInOrders==null)) {		
							if (GoodsInOrders.get(_OffersConditionsAssortmensRefItem.goods.id + _OffersConditionsAssortmensRefItem.offers_condition_id)!=null) {
								_OffersConditionsAssortmensRefItem.offers_condition_count_value = GoodsInOrders.get(_OffersConditionsAssortmensRefItem.goods.id + _OffersConditionsAssortmensRefItem.offers_condition_id);
							}
							else
							{
								_OffersConditionsAssortmensRefItem.offers_condition_count_value = 0;
							}  	
						}						
						
						_OffersConditionsAssortmensRefItem.offers_condition_sum_value = _OffersConditionsAssortmensRefItem.offers_condition_count_value *_OffersConditionsAssortmensRefItem.goods.price; 
						
						
						DocLine docit = DocumentClass.DocLineCollection.get(_OffersConditionsAssortmensRefItem.goods.id);
						if (!(docit==null)) {				
							_OffersConditionsAssortmensRefItem.indoc_count= docit.ordervalue*docit.factor;
							_OffersConditionsAssortmensRefItem.indoc_sum = docit.order_sum;							
						}	
						else
						{
							_OffersConditionsAssortmensRefItem.indoc_count= 0;
							_OffersConditionsAssortmensRefItem.indoc_sum = 0;
						}

						
						if (_OffersConditionsAssortmensRefItem.goods.isfolder==1){
							_OffersConditionsAssortmensRefItem.SubOffersConditionsAssortmensRefItem = new ArrayList<OffersConditionsAssortmensRefItem>(); 							
							GetOffersAssortmentByGroupId (_OffersConditionsAssortmensRefItem.goods.id,_OffersConditionsAssortmensRefItem);
						}
						
						_OffersRefItem.offers_assortmets_items.add(_OffersConditionsAssortmensRefItem);
						OffersConditionsAssortmensCursor.moveToNext();
						
					}
				}	
				
				OffersList.add(_OffersRefItem);
				
				OffersConditionsCursor.moveToNext();
			}		
		}
		
		 RecalculateOffer ();
		 
	}
	
	private void GetOffersGoodsInOrders () { 
		
		Cursor OffersGoodsInOrders = MainGlobalModule.DBE.rawQuery("select goods_id , offers_conditions_id , offervalue from xdoc_Orders_O where hdoc_id = ? and offers_id = ?", new String [] {DocumentClass.Head.id,Offer.id});		
		if (OffersGoodsInOrders.getCount()>0) {
			GoodsInOrders = new HashMap<String, Double>();
			OffersGoodsInOrders.moveToFirst();
			while (!OffersGoodsInOrders.isAfterLast()){
				GoodsInOrders.put(OffersGoodsInOrders.getString(0)+OffersGoodsInOrders.getString(1), OffersGoodsInOrders.getDouble(2));
				OffersGoodsInOrders.moveToNext();
			}
		}
		
	}
		
	private double getBonusCountValue (OffersBonusRefItem _OffersBonusRefItem) {
		
		Cursor OffersBonusCursor = MainGlobalModule.DBE.rawQuery("select sum (bonus_count) from xdoc_orders_b where hdoc_id = ? and offers_conditions_bonus_id = ?", new String []{DocumentClass.Head.id, _OffersBonusRefItem.id});
		if (OffersBonusCursor.getCount()>0) {
			OffersBonusCursor.moveToFirst();
			return (OffersBonusCursor.getDouble(0));
		}
		
		return (0);
	}
	
	private void GetOffersBonus () {
		
		Cursor OffersBonusCursor = MainGlobalModule.DBE.rawQuery("select id , offers_id , offers_conditions_id , goods_id , bonus_count , bonus_price , bonus_discount , bonus_numb ,comment from xref_Offers_Conditions_Bonus where offers_id = ?", new String [] {Offer.id});		
		if (OffersBonusCursor.getCount()>0) {
			bonus_List = new ArrayList<OffersBonusRefItem>();
			OffersBonusCursor.moveToFirst();
			
			while (!OffersBonusCursor.isAfterLast()){

				OffersBonusRefItem _OffersBonusRefItem = new OffersBonusRefItem ();
				_OffersBonusRefItem.id = OffersBonusCursor.getString(0);
				_OffersBonusRefItem.offers_id = OffersBonusCursor.getString(1);				
				 
				_OffersBonusRefItem.offers_conditions_id = OffersBonusCursor.getString(2);				
				if (_OffersBonusRefItem.offers_conditions_id.equals("     0   ")) {
					_OffersBonusRefItem.offers_conditions_id = null;
				}
				
				_OffersBonusRefItem.goods =  MainGlobalModule.GetGoodsRefItemByGoodsId(OffersBonusCursor.getString(3), CustomersPriceCategory ,DocumentClass.Head.firms_id, DocumentClass.Head.acctype, DocumentClass.Head.departments_id);
				_OffersBonusRefItem.bonus_count = OffersBonusCursor.getDouble(4);
				_OffersBonusRefItem.bonus_price = OffersBonusCursor.getDouble(5);
				_OffersBonusRefItem.bonus_discount = OffersBonusCursor.getDouble(6);
				_OffersBonusRefItem.bonus_numb = OffersBonusCursor.getInt(7);
				_OffersBonusRefItem.comment = OffersBonusCursor.getString(8);
				
				_OffersBonusRefItem.bonus_count_value = getBonusCountValue (_OffersBonusRefItem);
				
				bonus_List.add(_OffersBonusRefItem);				
				OffersBonusCursor.moveToNext();
				
			}			
		}		
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		
		requestWindowFeature(Window.FEATURE_NO_TITLE);            
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
	
		setContentView(R.layout.offersconditions_form);
		
		Ctx = this;
		
		Bundle DocExtras;
		DocExtras = getIntent().getExtras();
		
		tabs = (TabHost) findViewById(android.R.id.tabhost);

		tabs.setup();

		TabHost.TabSpec spec;				

		spec = tabs.newTabSpec("tag1");
		spec.setContent(R.id.tab1);
		spec.setIndicator("Условия");
		tabs.addTab(spec);		
		
		spec = tabs.newTabSpec("tag2");
		spec.setContent(R.id.tab2);
		spec.setIndicator("Бонусы");
		tabs.addTab(spec);
		
		
		Offer = new OffersRefItem();
		Offer.id = DocExtras.getString("id");
		Offer.descr = DocExtras.getString("descr");
		Offer.descr_full = DocExtras.getString("descr_full");
		Offer.offers_condition_type = DocExtras.getInt("offers_condition_type");
		Offer.offers_condition_logical_type = DocExtras.getInt("offers_condition_logical_type");		
		Offer.offers_condition_total_value  = DocExtras.getDouble("offers_condition_total_value");
		
		DocumentClass = (Documents_Order)MainGlobalModule.DocumentClass;		

		CustomersPriceCategory = MainGlobalModule.GetCustomerPriceCategoy(DocumentClass.Head.customers_id);
		
		GoodObject = new GoodRefObject (DocumentClass.Head.customers_id);
		if (GoodObject.DiscountRef.size()>0) {
			DiscountsEnable = MainGlobalModule.ConstantsCollection.get("DiscountsEnable").equals("true");
		}
		else
		{
			DiscountsEnable = false;
		}
		
		
		GetOffersBonus ();	
		GetOffersGoodsInOrders ();
		GetOffersConditions ();		
		
		offerscondition_descr = (TextView)findViewById(R.id.offerscondition_descr);
		offerscondition_descr.setText(Offer.descr);
		
		offerscondition_valuetype = (TextView)findViewById(R.id.offerscondition_valuetype);
		offerscondition_valuetype.setText(Offer.offers_condition_type==1?"Cумма":"Количество");
		
		offerscondition_logicaltype_descr = (TextView)findViewById(R.id.offerscondition_logicaltype_descr);
		offerscondition_logicaltype_descr.setText(Offer.offers_condition_logical_type==1?"Логика (И)":"Логика (ИЛИ)");
		
		offers_expandableListView = (ExpandableListView)findViewById (R.id.offers_expandableListView);
		offers_expandableListViewAdapter = new CustomExpandableListViewAdapter (this);
		offers_expandableListView.setAdapter(offers_expandableListViewAdapter);
		
		offers_expandableListView.setOnChildClickListener(new OnChildClickListener() {			
			@Override
			public boolean onChildClick(ExpandableListView parent, View v,int groupPosition, int childPosition, long id) {
			
				CurrentGroupIndx = groupPosition;
				CurrentChildIndx = childPosition;

				OffersConditionsAssortmensRefItem it = offers_expandableListViewAdapter.getGroup(CurrentGroupIndx).offers_assortmets_items.get(CurrentChildIndx);
				
				if (it.goods.isfolder == 1 & it.SubOffersConditionsAssortmensRefItem!=null) {
					
					Intent AssortmentList = new Intent ();AssortmentList.setClass(Ctx, Activity_OffersAssortments.class);					
					Bundle LX = new Bundle();					
					for  (OffersConditionsAssortmensRefItem itx : it.SubOffersConditionsAssortmensRefItem){
						LX.putDouble(itx.goods.id, itx.offers_condition_count_value);	
					}					
										
					LX.putString("id",it.offers_condition_id);		
					LX.putString("offers_id",it.offers_condition_id);
					LX.putInt("offers_condition_numb",0);		
					LX.putInt("offers_condition_sku_count",it.offers_condition_sku_count);
					LX.putDouble("offers_condition_value",it.offers_condition_value);		
					LX.putInt("offers_condition_sku_count_value",it.offers_condition_sku_count_value);
					LX.putDouble("offers_condition_count_value",it.offers_condition_count_value);
					LX.putDouble("offers_condition_sum_value",it.offers_condition_sum_value);
					AssortmentList.putExtras(LX);					
					startActivityForResult(AssortmentList, IDR_OpenSubChild);
					
				}
				else
				{
					Intent NumericPrompt = new Intent ();
					NumericPrompt.setClass(Ctx, Activity_NumericPrompt.class);
					NumericPrompt.putExtra("Numeric", it.offers_condition_count_value);				
					startActivityForResult(NumericPrompt, IDR_InputCountForChild);
				}
				
				
				return false;
			}
		});				
		
				
		offers_expandableListView.setOnItemLongClickListener(new OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id)  {
				
				int itemType = ExpandableListView.getPackedPositionType(id);				
				if(itemType == ExpandableListView.PACKED_POSITION_TYPE_GROUP) {
					
					int groupPosition = ExpandableListView.getPackedPositionGroup(id);
					
		  			CurrentGroupIndx = groupPosition;
					OffersConditionsRefItem ot = offers_expandableListViewAdapter.getGroup(CurrentGroupIndx);					
					Intent NumericPrompt = new Intent ();
					NumericPrompt.setClass(Ctx, Activity_NumericPrompt.class);
					NumericPrompt.putExtra("Numeric", ot.offers_condition_bonus_value);
					
					if (ot.offers_condition_ok_required>0){						
						startActivityForResult(NumericPrompt, IDR_InputCountForRequiredDistribute);
					}
					else
					{					
						startActivityForResult(NumericPrompt, IDR_InputCountForAutoDistribute);
					}
					return true;

		        }
				
				return false;
			}
		});
		

		
		OffersConditions_BackWard = (ImageView)findViewById(R.id.OffersConditions_BackWard);
		OffersConditions_BackWard.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				FinishActivity ();				
			}
		});
		
		OffersConditions_DescriptionButton = (ImageView)findViewById(R.id.OffersConditions_DescriptionButton);
		OffersConditions_DescriptionButton.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				
				AlertDialog.Builder builder = new AlertDialog.Builder(Ctx);
				builder.setTitle("Условия акциии");
				builder.setMessage(Offer.descr_full);
				builder.create().show();
				
			}
		});
		
		tabs.setOnTabChangedListener(TabChange_Click);		
		tabs.setCurrentTab(0);		
		
		bonus_ListView = (ListView)findViewById(R.id.offers_bonuslistview);
		bonus_ListViewAdapter = new CustomListViewAdapter(this);
		bonus_ListView.setAdapter(bonus_ListViewAdapter);
		bonus_ListView.setOnItemClickListener(bonus_ListView_Click);
		
		int count = offers_expandableListViewAdapter.getGroupCount();
		
		for (int position = 1; position <= count; position++)
			offers_expandableListView.expandGroup(position - 1);
		}
			
	private AdapterView.OnItemClickListener  bonus_ListView_Click = new AdapterView.OnItemClickListener () {
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {			
			
			CurrentBonusesIndx = arg2;
			Intent NumericPrompt = new Intent ();
			NumericPrompt.setClass(Ctx, Activity_NumericPrompt.class);
			NumericPrompt.putExtra("Numeric", 0);				
			startActivityForResult(NumericPrompt, IDR_InputCountForBonuses);
			
		}
	};
	
	private OnTabChangeListener TabChange_Click = new OnTabChangeListener() {		
		@Override
		public void onTabChanged(String tabId) {
				
			
		}
	};
	
	private void RecalculateOffer () {			
		
		for (OffersConditionsRefItem oi : OffersList) {			
			
			oi.offers_condition_sku_count_value = 0;					
			oi.offers_condition_count_value = 0;
			oi.offers_condition_sum_value = 0;
			
			oi.offers_condition_ok_required = 0;
			oi.offers_condition_ok_count = 0;
			oi.offers_condition_ok_min = 999999;			
			
			for (OffersConditionsAssortmensRefItem itx : oi.offers_assortmets_items) {
				
				// РАСЧЕТ ВЛОЖЕННОГО АССОРТИМЕНТА
				if (itx.SubOffersConditionsAssortmensRefItem!=null) {
					itx.offers_condition_sku_count_value = 0;
					itx.offers_condition_count_value = 0;
					itx.offers_condition_sum_value = 0;					
					for (OffersConditionsAssortmensRefItem its : itx.SubOffersConditionsAssortmensRefItem) {						
						if (its.offers_condition_count_value>0){
							itx.offers_condition_sku_count_value +=1;
							itx.offers_condition_count_value += its.offers_condition_count_value;
							itx.offers_condition_sum_value += its.offers_condition_count_value * its.goods.price;
						}	
					}
				}
				
				// РАЧЕТ СУМ И МНОЖИТЕЛЕЙ				
				if (itx.goods.isfolder!=1) {
					itx.offers_condition_sum_value = itx.offers_condition_count_value * itx.goods.price;	
				}
				itx.offers_condition_ok_value = (int)itx.offers_condition_count_value / (itx.offers_condition_value == 0? 1:itx.offers_condition_value);
				
				// РАСЧЕТ ИТОГОВ ПО УСЛОВИЯМ
				oi.offers_condition_sku_count_value += itx.offers_condition_count_value > 0 ? 1:0;					
				oi.offers_condition_count_value += itx.offers_condition_count_value;
				oi.offers_condition_sum_value += itx.offers_condition_sum_value;
				
				oi.offers_condition_ok_required += itx.offers_condition_value> 0 ? 1:0;
				
				oi.offers_condition_ok_count += itx.offers_condition_ok_value> 0 ? 1:0;
				
				oi.offers_condition_ok_min = itx.offers_condition_ok_value<oi.offers_condition_ok_min?itx.offers_condition_ok_value:oi.offers_condition_ok_min;
				
				
				
			}		
			
			// bonus calculate
			double BonusCountValue  = 0;
			
			if (oi.offers_condition_ok_required>0){
				BonusCountValue = (double)oi.offers_condition_ok_min;
			}
			else
			{
				// в условиях нет множителей
		        if (oi.offers_condition_value>0){	        		        	
		        	switch (Offer.offers_condition_type) {
		        	case (1):						
		        		BonusCountValue = (int) (oi.offers_condition_sum_value / oi.offers_condition_value);						
						break;
		        	case (2):
		        		BonusCountValue = (int) (oi.offers_condition_count_value / (oi.offers_condition_value));
						break;
		        	default:
		        		break;
		        	};					
		        }				
			}		
	        
	        
			
			if (oi.offers_condition_sku_count > 0 ){
				int BonusSKUValue = oi.offers_condition_sku_count_value/oi.offers_condition_sku_count;
				if (BonusSKUValue<BonusCountValue) {
					BonusCountValue = BonusSKUValue; 
				}
			}
	        
			oi.offers_condition_bonus_value = BonusCountValue;
			
			
			/// если условие = 0 тогда факт наличия хотя бы одного товара из ассортимента соотв бонусов = 1
			if (oi.offers_condition_value ==0 & (oi.offers_condition_count_value>0 | oi.offers_condition_sum_value>0 )) {
				BonusCountValue = 1;
				oi.offers_condition_bonus_value = BonusCountValue;
			}
			
			// РАСПРЕДЕЛЕНИЕ БОНУСОВ
			
			// определим список бонусов для распределения
			ArrayList<OffersBonusRefItem> InBonus = new ArrayList<OffersBonusRefItem> ();			
			int OrderBonusValue = 0;			
			for (OffersBonusRefItem bi :bonus_List) {
				if (bi.offers_conditions_id!=null){
					if (bi.offers_conditions_id.equals(oi.id)){
						OrderBonusValue += bi.bonus_count_value; 
						InBonus.add(bi);
					}					
				}
				else
				{					
					OrderBonusValue += bi.bonus_count_value;
					InBonus.add(bi);										
				}
			}

			
			if (BonusCountValue>0) {
				if ((OrderBonusValue!=BonusCountValue)) {
					int mod = (int)BonusCountValue/InBonus.size();
					for (OffersBonusRefItem bi :InBonus) {
						bi.bonus_count_value = mod;
						BonusCountValue -= mod;
					}
					if ((BonusCountValue>0)&(InBonus.size()>0)) {
						OffersBonusRefItem bi  = InBonus.get(0);
						bi.bonus_count_value += BonusCountValue;
					}				
				}
			}
			else
			{
				for (OffersBonusRefItem bi :InBonus) {
					bi.bonus_count_value = 0;
				}
			}
			
			
		}
				
	}
	
	private void insertToOthersConditions (String itx_goods_id, String itx_offers_condition_id, double itx_offers_condition_count_value) {		
			
		for (OffersConditionsRefItem oi:OffersList) {
			if (!(oi.id.equals(itx_offers_condition_id))) {
				for (OffersConditionsAssortmensRefItem itx : oi.offers_assortmets_items) {
					if (itx.goods.id.equals(itx_goods_id)) {
						itx.offers_condition_count_value = itx_offers_condition_count_value;
					}
					if (itx.SubOffersConditionsAssortmensRefItem!=null) {				
						for (OffersConditionsAssortmensRefItem its : itx.SubOffersConditionsAssortmensRefItem) {						
							if (its.goods.id.equals(itx_goods_id)) {
								its.offers_condition_count_value = itx_offers_condition_count_value;
							}
						}
					}					
				}	
			}
		}
		
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		if (resultCode == RESULT_OK) {

			OffersConditionsRefItem ig = offers_expandableListViewAdapter.getGroup(CurrentGroupIndx);
			OffersConditionsAssortmensRefItem it = ig.offers_assortmets_items.get(CurrentChildIndx);
			
			switch (requestCode) {
			
				case IDR_InputCountForChild:
					it.offers_condition_count_value = data.getDoubleExtra("NumericValue", 0);
					break;
					
				case IDR_OpenSubChild:
					it.offers_condition_count_value = data.getDoubleExtra("NumericValue", 0);					
					Bundle DocExtras = data.getExtras();
					
					for (OffersConditionsAssortmensRefItem itx : it.SubOffersConditionsAssortmensRefItem ) {						
						itx.offers_condition_count_value = DocExtras.getDouble(itx.goods.id);
						insertToOthersConditions (itx.goods.id,itx.offers_condition_id,itx.offers_condition_count_value);
					}
					
					break;
					
				case IDR_InputCountForRequiredDistribute:
					for (OffersConditionsAssortmensRefItem itx : ig.offers_assortmets_items){
						itx.offers_condition_count_value = itx.offers_condition_value*data.getDoubleExtra("NumericValue", 0);						
					}
					break;
					
				case IDR_InputCountForAutoDistribute:
					
					
					int isgroup = 0;
					for (OffersConditionsAssortmensRefItem itx : ig.offers_assortmets_items){
						if (itx.goods.isfolder==1){
							isgroup = 1;
							break;
						}
					};				
					
					if (isgroup==0) {
						Double TotalCountToDistribute = data.getDoubleExtra("NumericValue", 0)*ig.offers_condition_value;
						int LineCountToDistribute = (int) (TotalCountToDistribute/ig.offers_assortmets_items.size());											
						for (OffersConditionsAssortmensRefItem itx : ig.offers_assortmets_items){
							itx.offers_condition_count_value = LineCountToDistribute; 
							TotalCountToDistribute -= LineCountToDistribute;
						}
						ig.offers_assortmets_items.get(0).offers_condition_count_value += TotalCountToDistribute;
					}					
					
					break;
					
				case IDR_InputCountForBonuses:
				
					// узнаем какое условие сработало
					OffersConditionsRefItem oit;
					double FreeBonuses = 0;
					double BonusCount = 0;
				
					for (OffersConditionsRefItem oi: OffersList) {
						if (oi.offers_condition_bonus_value>0) {
							oit = oi;						
							// 	посчитаем распределенные бонусы						
							for (OffersBonusRefItem bix :bonus_List) {
								if (oit.id.equals(bix.offers_conditions_id)&bix.bonus_count_value>0) {
									BonusCount++;
								}
							}						
							FreeBonuses = oit.offers_condition_bonus_value - BonusCount;	
							double input_bonuses = data.getDoubleExtra("NumericValue", 0);						
							if (FreeBonuses>=input_bonuses) {
								if (bonus_List.get(CurrentBonusesIndx).offers_conditions_id.equals(oit.id)) {
									bonus_List.get(CurrentBonusesIndx).bonus_count_value = input_bonuses;
									bonus_ListViewAdapter.notifyDataSetChanged();
								}
							}						
							break;						
						}
					}
				
				return;
				
			default:
				break;
			}
			
			RecalculateOffer ();	
			
			offers_expandableListViewAdapter.notifyDataSetChanged();
			bonus_ListViewAdapter.notifyDataSetChanged();			
			
			Toast.makeText(Ctx, String.format("%.2f / %.2f", ig.offers_condition_value , ig.offers_condition_count_value) , Toast.LENGTH_SHORT).show();			 
			
		}		
		
	}
		
	private class CustomExpandableListViewAdapter extends BaseExpandableListAdapter {

		Context context;
		
		public CustomExpandableListViewAdapter (Context context) {
			this.context = context;
		}
		
		@Override
		public OffersConditionsAssortmensRefItem getChild(int groupPosition, int childPosition) { 
			return offers_expandableListViewAdapter.getGroup(CurrentGroupIndx).offers_assortmets_items.get(CurrentChildIndx);
		}

		@Override
		public long getChildId(int groupPosition, int childPosition) {
			return childPosition;			
		}

		@Override
		public View getChildView(int groupPosition, int childPosition,boolean isLastChild, View convertView, ViewGroup parent) {
			
			if (convertView == null) {
		            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		            convertView = inflater.inflate(R.layout.offersconditions_form_sublist, null);
		    }
			
			convertView.setBackgroundColor(Color.rgb(0, 0, 0));
			
			
			OffersConditionsAssortmensRefItem it = OffersList.get(groupPosition).offers_assortmets_items.get(childPosition);
			
			TextView offerscondass_descr = (TextView) convertView.findViewById(R.id.offerscondass_descr);
			offerscondass_descr.setTextColor(Color.WHITE);
			offerscondass_descr.setText(it.goods.descr);
			
			TextView offerscondass_price = (TextView) convertView.findViewById(R.id.offerscondass_price);
			offerscondass_price.setText(String.format("ц.%.2f", it.goods.price));
			if (it.goods.isfolder==1) {
				offerscondass_price.setVisibility(View.INVISIBLE);
			}
			else
			{
				offerscondass_price.setVisibility(View.VISIBLE);
			};
			
			TextView offerscondass_rest = (TextView) convertView.findViewById(R.id.offerscondass_rest);
			offerscondass_rest.setText(String.format("о.%.2f %s", it.goods.rest,it.goods.measure_base_descr));
			if (it.goods.isfolder==1) {
				offerscondass_rest.setVisibility(View.INVISIBLE);
			}
			else
			{
				offerscondass_rest.setVisibility(View.VISIBLE);
				if (it.goods.rest<=0) {
					offerscondass_descr.setTextColor(Color.DKGRAY);	
				}
			};
			
						
			TextView offerscondass_value = (TextView) convertView.findViewById(R.id.offerscondass_value);
			offerscondass_value.setText(String.format("%.2f",it.offers_condition_value));
			if (it.offers_condition_value==0){
				offerscondass_value.setText("");
			}
			
			TextView offerscondass_value_count = (TextView) convertView.findViewById(R.id.offerscondass_value_count);
			offerscondass_value_count.setText(String.format("%.2f",it.offers_condition_count_value));

			TextView offerscondass_value_sum = (TextView) convertView.findViewById(R.id.offerscondass_value_sum);
			offerscondass_value_sum.setText(String.format("%.2f",it.offers_condition_sum_value));

			TextView offerscondass_ordercount = (TextView) convertView.findViewById(R.id.offerscondass_ordercount);
			TextView offerscondass_ordersum = (TextView) convertView.findViewById(R.id.offerscondass_ordersum);			
			
			offerscondass_ordercount.setVisibility(View.INVISIBLE);
			offerscondass_ordersum.setVisibility(View.INVISIBLE);
			
			if (it.indoc_count>0) {
				offerscondass_ordercount.setText(String.format("%.2f %s",it.indoc_count,it.goods.isfolder==1?"ед.":it.goods.measure_base_descr));
				offerscondass_ordersum.setText(String.format("%.2f",it.indoc_sum));
				offerscondass_ordercount.setVisibility(View.VISIBLE);
				offerscondass_ordersum.setVisibility(View.VISIBLE);				
				if (it.indoc_count >= it.offers_condition_value) {
					convertView.setBackgroundColor(Color.rgb(130, 130, 130));				
				}	
			}
			
			if ((it.offers_condition_count_value > 0) & (it.offers_condition_count_value >= it.offers_condition_value)) {
				convertView.setBackgroundColor(Color.rgb(118, 39, 95));
			}
			
			TextView offers_condition_ok_value = (TextView) convertView.findViewById(R.id.offers_condition_ok_value);
			offers_condition_ok_value.setVisibility(View.INVISIBLE);
			if ((it.offers_condition_value > 0) & (it.offers_condition_ok_value>0)) {
				offers_condition_ok_value.setVisibility(View.VISIBLE);	
				offers_condition_ok_value.setText(String.format("%.0f",it.offers_condition_ok_value ));
			}
			
			
			
		    return convertView;
		      
		}

		@Override
		public int getChildrenCount(int groupPosition) {
			return  OffersList.get(groupPosition).offers_assortmets_items.size();			
		}

		@Override
		public OffersConditionsRefItem getGroup(int groupPosition) {
			return OffersList.get(groupPosition);
		}

		@Override
		public int getGroupCount() {
			return OffersList.size();
		}

		@Override
		public long getGroupId(int groupPosition) {			
			return groupPosition;
		}

		@Override
		public View getGroupView(int groupPosition, boolean isExpanded, View convertView,ViewGroup parent) {
			
		       if (convertView == null) {
		            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		            convertView = inflater.inflate(R.layout.offersconditions_form_list, null);
		        }

		        OffersConditionsRefItem it = offers_expandableListViewAdapter.getGroup(groupPosition);
		        
		        TextView offerscond_numb = (TextView) convertView.findViewById(R.id.offerscond_numb);
		        offerscond_numb.setText(String.format("[%d]", it.offers_condition_numb));
		        
		        TextView offerscond_sku_count = (TextView) convertView.findViewById(R.id.offerscond_sku_count);		        
		        if (it.offers_condition_sku_count != 0) {
		        	offerscond_sku_count.setVisibility(View.VISIBLE);
		        	offerscond_sku_count.setText(String.format("SKU:(%d / %d)", it.offers_condition_sku_count, it.offers_condition_sku_count_value));
		        }
		        else
		        {
		        	offerscond_sku_count.setVisibility(View.INVISIBLE);
		        }		        
		        
		        TextView offerscond_value_count = (TextView) convertView.findViewById(R.id.offerscond_value_count);
		        switch (Offer.offers_condition_type) {
					case 0:
						offerscond_value_count.setText(String.format("%s:( %.2f / %.2f)","Кол-во", it.offers_condition_value,it.offers_condition_count_value));	
					break;					
					case 1:
						offerscond_value_count.setText(String.format("%s:( %.2f / %.2f)","Сумма",it.offers_condition_value,it.offers_condition_sum_value));
					break;
					case 2:
						offerscond_value_count.setText(String.format("%s:( %.2f / %.2f)","Кол-во", it.offers_condition_value,it.offers_condition_count_value));	
					break;	

				default:
					break;
				}		        
		        
		        TextView offerscond_value_sum = (TextView) convertView.findViewById(R.id.offerscond_value_sum);
		        offerscond_value_sum.setText(String.format("Сумма:%.2f",it.offers_condition_sum_value));
				
				TextView offerscond_bonus_count = (TextView) convertView.findViewById(R.id.offerscond_bonus_count);		        
				offerscond_bonus_count.setText(String.format("бонус x %.0f", it.offers_condition_bonus_value));
				
		        if (it.offers_condition_bonus_value>0) {
		        	convertView.setBackgroundColor(Color.rgb(255, 102, 0));		        	
		        }
		        else
		        {
		        	convertView.setBackgroundColor(Color.rgb(255, 255, 0));
		        }

		        return convertView;
			
		}

		@Override
		public boolean hasStableIds() {
			// TODO Auto-generated method stub
			return true;
		}

		@Override
		public boolean isChildSelectable(int groupPosition, int childPosition) {		
			return true;
		}
		
	}
	
	/// прорисовка бонусов
	private class CustomListViewAdapter extends BaseAdapter  {

		private LayoutInflater mInflater;
		public Context context;		
		  
		public CustomListViewAdapter(Context context) { 
			
			mInflater = LayoutInflater.from(context);
			this.context = context;
			
		}
		
		
		/// прорисовка бонусов
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
		    
			ViewHolder holder;
			
			if (convertView == null) {			
				convertView = mInflater.inflate(R.layout.offersbonus_form_list, null);
			}
			
			holder = new ViewHolder();
			
			OffersBonusRefItem it  = getItem(position);
			
			holder.num = (TextView)convertView.findViewById(R.id.offersbonusllist_num);
			holder.bonus = (TextView)convertView.findViewById(R.id.offersbonuslist_bonus);
			holder.bonuscount = (TextView)convertView.findViewById(R.id.offersbonuslist_bonuscount);						
			
			holder.num.setText(String.format ("[%s]",it.bonus_numb));			
			
			if (it.goods!=null){
				holder.bonus.setText(String.format ("%s",it.goods.descr));				
			}
			else
			{
				holder.bonus.setText(String.format ("%s",it.comment));
			}
			
			if (it.bonus_count>0){
				holder.bonuscount.setText(String.format ("%.2f %s x %.0f",it.bonus_count, it.goods == null?"шт.":it.goods.measure_base_descr,it.bonus_count_value));
			}
			
			if (it.bonus_price>0){
				holder.bonuscount.setText(String.format ("ц.%.2f",it.bonus_price));
			}	
			
			if (it.bonus_discount>0){
				holder.bonuscount.setText(String.format ("ск.%.2f",it.bonus_discount));
			}	
			
			if (it.bonus_count_value>0){
				convertView.setBackgroundColor(Color.MAGENTA);				
			}
			else
			{
				convertView.setBackgroundColor(Color.BLACK);
			}
			
			
			return convertView;
			
		}
		
		@Override
		public int getCount() {			
			return bonus_List.size();
		}

		@Override
		public OffersBonusRefItem getItem(int arg0) {		
			return bonus_List.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {			
			return bonus_List.get(arg0).id.hashCode();
		}		
		
		class ViewHolder {
			
			TextView num;
			TextView bonus;
			TextView bonuscount;
				
		}
			 
		
	}

}
